package com.ibeeking.found.cop.b.rest.service.impl;

import com.ibeeking.found.common.constants.WxCpServiceTypeConstant;
import com.ibeeking.found.common.entity.open.*;
import com.ibeeking.found.common.enums.OpenApiConfigEnum;
import com.ibeeking.found.common.enums.WxCpAppTypeEnum;
import com.ibeeking.found.common.response.ResponseCodeEnum;
import com.ibeeking.found.common.utils.DataUtils;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.found.cop.b.rest.config.prop.RedisProperties;
import com.ibeeking.found.cop.b.rest.service.IWxOpenService;
import com.ibeeking.found.cop.service.common.constants.RedisKeyConstant;
import com.ibeeking.gmc.global.api.feign.GlobalOpenFeignClient;
import com.ibeeking.nematos.core.utils.SpringBeanUtil;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.redis.utils.RedisUtils;
import com.ibeeking.nematos.utils.json.JsonUtils;
import com.ibeeking.nematos.utils.result.ResponseResult;
import me.chanjar.weixin.common.bean.WxAccessToken;
import me.chanjar.weixin.common.redis.JedisWxRedisOps;
import me.chanjar.weixin.common.redis.RedisTemplateWxRedisOps;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpProviderToken;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import me.chanjar.weixin.cp.config.WxCpTpConfigStorage;
import me.chanjar.weixin.cp.config.impl.WxCpJedisConfigImpl;
import me.chanjar.weixin.cp.config.impl.WxCpRedissonConfigImpl;
import me.chanjar.weixin.cp.config.impl.WxCpTpRedissonConfigImpl;
import me.chanjar.weixin.cp.tp.service.WxCpTpService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 禁止在此类加其他业务方法
 *
 * @ClassName WxMpService
 * @Description
 * @Author ibeeking
 * @Date 2020-12-30 10:29
 **/
@Service
@EnableConfigurationProperties({RedisProperties.class})
public class WxOpenServiceImpl implements IWxOpenService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    //30分钟
    private static final Long TIME = 7000L;

    @Resource
    private GlobalOpenFeignClient globalOpenFeignClient;

    @Autowired
    private RedisProperties redisProperties;

    @Resource
    private RedisUtils redisUtils;

    @Override
    public OpenConfigDTO queryWxOpenConfigByType(Integer configType, Integer configSubType) {
        OpenConfigQuery query = new OpenConfigQuery();
        query.setType(configType);
        query.setSubType(configSubType);
        ResponseResult<OpenConfigDTO> responseResult = globalOpenFeignClient.queryOpenConfigOne(query);
        return responseResult.getData();
    }

    @Override
    public OpenAuthDTO queryWxOpenAuthByByAppId(Long tenantId, String appId) {
        OpenAuthQuery query = new OpenAuthQuery();
        query.setTenantId(tenantId);
        query.setAppId(appId);
        ResponseResult<OpenAuthDTO> responseResult = globalOpenFeignClient.queryOpenAuthOne(query);
        DataUtils.trueThrowException(!ResponseCodeEnum.SUCCESS.getCode().equals(responseResult.getCode()), responseResult.getMsg());
        return responseResult.getData();
    }

    @Override
    public OpenAuthDTO queryWxOpenAuthByTenantId(Long tenantId, Integer configType, Integer configSubType, Integer appType) {
        OpenAuthQuery query = new OpenAuthQuery();
        query.setTenantId(tenantId);
        query.setConfigType(configType);
        query.setConfigSubType(configSubType);
        query.setAppType(appType);
        ResponseResult<OpenAuthDTO> responseResult = globalOpenFeignClient.queryOpenAuthOne(query);
        return responseResult.getData();
    }

    /**
     * 获取开放平台服务并将注册为bean
     *
     * @param
     * @return
     */
    @Override
    public WxCpService getWxCpService(Long tenantId) {
        try {
            OpenConfigDTO wxOpenConfigDTO = queryWxOpenConfigByType(OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode(), WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_SB.getCode());
            if(wxOpenConfigDTO==null)  throw new BusinessException("企业微信自建应用OpenConfigDTO没有配置，请先配置!");

            OpenAuthDTO  wxOpenAuthDTO = queryWxOpenAuthByTenantId(tenantId, OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode(), WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_SB.getCode(), WxCpServiceTypeConstant.CP_TYPE_SB);
            if(wxOpenAuthDTO == null) throw new BusinessException("企业微信自建应用OpenAuthDTO没有配置，请先配置!");
            WxCpService wxcCpService = SpringBeanUtil.getBean(WxCpService.class);
            if(wxcCpService == null) throw new BusinessException("get WxOpenService service error!");
            WxCpConfigStorage wxCpConfigStorage = getWxCpRedissonConfigStorage(tenantId, wxOpenConfigDTO, wxOpenAuthDTO);
            LogUtils.info(">>>>>>>>>>>>>自建应用ConfigStorage:{}", JsonUtils.toJsonStr(wxCpConfigStorage));

            wxcCpService.setWxCpConfigStorage(wxCpConfigStorage);
            wxcCpService.getAccessToken(true);
            return wxcCpService;
        }catch(Exception ex){
            LogUtils.error(ex.toString());
            return null;
        }
    }
    /**
     * 获取开放平台服务并将注册为bean
     *
     * @param
     * @return
     */
    @Override
    public WxCpTpService getWxCpTpService(Long tenantId) {
        try {
            OpenConfigDTO wxOpenConfigDTO = queryWxOpenConfigByType(OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode(), WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_TP.getCode());
            OpenAuthDTO wxOpenAuthDTO =  queryWxOpenAuthByTenantId(tenantId, OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode(), WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_TP.getCode(), WxCpServiceTypeConstant.CP_TYPE_TP);

            WxCpTpService wxCpDkService = SpringBeanUtil.getBean(WxCpTpService.class);
            if (wxCpDkService == null) throw new BusinessException("get wxCpTpService service error!");
            WxCpTpConfigStorage wxCpDkConfigStorage = getWxCpTpRedissonConfigStorage(tenantId, wxCpDkService, wxOpenConfigDTO, wxOpenAuthDTO);
            LogUtils.info(">>>>>>>>>>>>>三方应用ConfigStorage:{}", JsonUtils.toJsonStr(wxCpDkConfigStorage));
            wxCpDkService.setWxCpTpConfigStorage(wxCpDkConfigStorage);
            return wxCpDkService;
        }catch(Exception ex){
            LogUtils.error(ex.toString());
            return null;
        }
    }

    @Override
    public String getWxCpTpAccessToken(Long tenantId){
        OpenAuthDTO openAuthDTO =  queryWxOpenAuthByTenantId(tenantId, OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode(), WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_TP.getCode(), WxCpServiceTypeConstant.CP_TYPE_TP);
        if(openAuthDTO == null) throw new BusinessException("企业微信自建应用没有配置，请先配置!");
        OpenAuthOfExtend openAuthOfExtend = openAuthDTO.getOpenAuthOfExtend();
        if(openAuthOfExtend == null) throw new BusinessException("企业微信自建应用没有配置，请先配置!");
        OpenAuthOfWxCpTp  openAuthOfWxCpTp = openAuthOfExtend.getOpenAuthOfWxCpTp();
        return openAuthOfWxCpTp.getCorpAccessToken();
    }
    /**
     * 获取开放平台服务并将注册为bean
     *
     * @param
     * @return
     */
    @Override
    public WxCpTpService getWxCpDkService(Long tenantId) {
        try {
            OpenConfigDTO wxOpenConfigDTO = queryWxOpenConfigByType(OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode(), WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_DK.getCode());
            OpenAuthDTO wxOpenAuthDTO =  queryWxOpenAuthByTenantId(tenantId, OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode(), WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_DK.getCode(), WxCpServiceTypeConstant.CP_TYPE_DK);

            WxCpTpService wxCpDkService = SpringBeanUtil.getBean(WxCpTpService.class);
            if (wxCpDkService == null) throw new BusinessException("get wxCpDkService service error!");
            WxCpTpConfigStorage wxCpDkConfigStorage = getWxCpDkRedissonConfigStorage(tenantId, wxCpDkService, wxOpenConfigDTO, wxOpenAuthDTO);
            LogUtils.info(">>>>>>>>>>>>>代开应用ConfigStorage:{}", JsonUtils.toJsonStr(wxCpDkConfigStorage));
            wxCpDkService.setWxCpTpConfigStorage(wxCpDkConfigStorage);
            return wxCpDkService;
        }catch(Exception ex){
            LogUtils.error(ex.toString());
            return null;
        }
    }

    private WxCpConfigStorage getWxCpRedissonConfigStorage(Long tenantId, OpenConfigDTO wxOpenConfigDTO, OpenAuthDTO wxOpenAuthDTO) {
        OpenAuthOfExtend openAuthOfExtend = wxOpenAuthDTO.getOpenAuthOfExtend();
        if(openAuthOfExtend == null) throw new BusinessException("企业微信自建应用没有配置，请先配置!");
        OpenAuthOfWxCpSb  openAuthOfWxCpSb = openAuthOfExtend.getOpenAuthOfWxCpSb();
        WxCpJedisConfigImpl wxCpJedisConfigImpl = new WxCpJedisConfigImpl(redisProperties.getJedisPool(), "wx:cp:sb:".concat(tenantId.toString()));

        wxCpJedisConfigImpl.setCorpId(wxOpenAuthDTO.getOpenAppId());
        wxCpJedisConfigImpl.setCorpSecret(wxOpenAuthDTO.getAppSecret());
        wxCpJedisConfigImpl.setToken(wxOpenAuthDTO.getAppToken());
        wxCpJedisConfigImpl.setAesKey(wxOpenAuthDTO.getAppAesKey());
        OpenConfigOfExtend openConfigOfExtend = wxOpenConfigDTO!=null?wxOpenConfigDTO.getOpenConfigOfExtend():null;
        OpenConfigOfWxCp openConfigOfWxCp = openConfigOfExtend!=null?openConfigOfExtend.getOpenConfigOfWxCp():null;
        OpenConfigOfWxCpTalkData openConfigOfWxCpTalkData = openConfigOfWxCp!=null?openConfigOfWxCp.getWxCpTalkData():null;
        if(openConfigOfWxCpTalkData!=null) {
            wxCpJedisConfigImpl.setMsgAuditSecret(openConfigOfWxCpTalkData.getTalkDataSecret());
            wxCpJedisConfigImpl.setMsgAuditPriKey(openConfigOfWxCpTalkData.getTalkDataPriKey());
            wxCpJedisConfigImpl.setMsgAuditLibPath(openConfigOfWxCpTalkData.getTalkDataLibPath());
        }
        if(StringUtils.isNotEmpty(wxOpenAuthDTO.getAppId())) {
            Integer agentId  = Integer.parseInt(wxOpenAuthDTO.getAppId());
            wxCpJedisConfigImpl.setAgentId(agentId);
        }
        if(StringUtils.isNotEmpty(openAuthOfWxCpSb.getAccessToken())){
            WxAccessToken wxAccessToken = new WxAccessToken();
            wxAccessToken.setAccessToken(openAuthOfWxCpSb.getAccessToken());
            wxAccessToken.setExpiresIn(openAuthOfWxCpSb.getAccessTokenExpiresTime());
            wxCpJedisConfigImpl.updateAccessToken(wxAccessToken);
        }
        return wxCpJedisConfigImpl;
    }

    private WxCpTpConfigStorage getWxCpTpRedissonConfigStorage(Long tenantId, WxCpTpService wxCpTpService, OpenConfigDTO openConfigDTO, OpenAuthDTO openAuthDTO ) {
        OpenAuthOfExtend openAuthOfExtend = openAuthDTO.getOpenAuthOfExtend();
        if(openAuthOfExtend == null) throw new BusinessException("企业微信自建应用没有配置，请先配置!");
        OpenAuthOfWxCpTp  openAuthOfWxCpTp = openAuthOfExtend.getOpenAuthOfWxCpTp();
        String authCorpAppId = null;
        OpenAuthOfWxCpTpAuthCorpInfo authCorpInfo = openAuthOfWxCpTp.getAuthCorpInfo();
        if(authCorpInfo!=null) authCorpAppId = authCorpInfo.getCorpid();
        WxCpTpConfigStorage configStorage = wxCpTpService.getWxCpTpConfigStorage();
        Integer configType = openConfigDTO.getType();
        Integer configSubType = openConfigDTO.getSubType();
        JedisWxRedisOps  wxRedisOps = new JedisWxRedisOps(redisProperties.getJedisPool());
        String openConfigKey = "wx:cp:tp:t".concat(configType.toString()).concat(":s").concat(configSubType.toString());
        String suiteId = openConfigDTO.getComponentAppId();
        WxCpTpRedissonConfigImpl.WxCpTpRedissonConfigImplBuilder configStorageBuider = WxCpTpRedissonConfigImpl.builder().wxRedisOps(wxRedisOps);
        if(StringUtils.isNotEmpty(openConfigKey))configStorageBuider.keyPrefix(openConfigKey);
        if(StringUtils.isNotEmpty(openConfigDTO.getOpenAppId()))configStorageBuider.corpId(openConfigDTO.getOpenAppId());
        if(StringUtils.isNotEmpty(openConfigDTO.getOpenAppSecret()))configStorageBuider.corpSecret(openConfigDTO.getOpenAppSecret());
        if(StringUtils.isNotEmpty(openConfigDTO.getComponentAppId()))configStorageBuider.suiteId(suiteId);
        if(StringUtils.isNotEmpty(openConfigDTO.getComponentSecret()))configStorageBuider.suiteSecret(openConfigDTO.getComponentSecret());
        if(StringUtils.isNotEmpty(openConfigDTO.getComponentMsgToken()))configStorageBuider.token(openConfigDTO.getComponentMsgToken());
        if(StringUtils.isNotEmpty(openConfigDTO.getComponentMsgAesKey()))configStorageBuider.aesKey(openConfigDTO.getComponentMsgAesKey());
        if(StringUtils.isNotEmpty(openConfigDTO.getHttpProxyHost()))configStorageBuider.httpProxyHost(openConfigDTO.getHttpProxyHost());
        if(null!=openConfigDTO.getHttpProxyPort())configStorageBuider.httpProxyPort(openConfigDTO.getHttpProxyPort());
        if(StringUtils.isNotEmpty(openConfigDTO.getHttpProxyUsername()))configStorageBuider.httpProxyUsername(openConfigDTO.getHttpProxyUsername());
        if(StringUtils.isNotEmpty(openConfigDTO.getHttpProxyPassword()))configStorageBuider.httpProxyPassword(openConfigDTO.getHttpProxyPassword());

        configStorage = configStorageBuider.build();
        Long currentSysteTime = System.currentTimeMillis();
        String suiteTicket = redisUtils.getString(RedisKeyConstant.WX_CP_TP_SUITE_TICKET.concat(suiteId));
        Object suiteAccessTokenObj = redisUtils.get(RedisKeyConstant.WX_CP_TP_SUITE_ACCESS_TOKEN.concat(suiteId));
        // ticket
        if(StringUtils.isEmpty(suiteTicket)){
            configStorage.updateSuiteTicket(openAuthOfWxCpTp.getSuiteTicket(), 1200);
            redisUtils.set(RedisKeyConstant.WX_CP_TP_SUITE_TICKET + suiteId, openAuthOfWxCpTp.getSuiteTicket(),1000);
        }else{
            configStorage.updateSuiteTicket(suiteTicket, 1200);
        }
        //update suiteAccessToken
        Long suiteAccessTokenExpiresIn =  openAuthOfWxCpTp.getSuiteAccessExpirein();
        Long suiteAccessTokenExpiresTimes = suiteAccessTokenExpiresIn!=null?(suiteAccessTokenExpiresIn-currentSysteTime)/1000:7000;
        if(ObjectUtils.isEmpty(suiteAccessTokenObj)) {
            configStorage.updateSuiteAccessToken(openAuthOfWxCpTp.getSuiteAccessToken(), suiteAccessTokenExpiresTimes>0?suiteAccessTokenExpiresTimes.intValue():7000);
            WxAccessToken suiteAccessTokenEntity = new WxAccessToken();
            suiteAccessTokenEntity.setAccessToken(openAuthOfWxCpTp.getSuiteAccessToken());
            suiteAccessTokenEntity.setExpiresIn(suiteAccessTokenExpiresTimes>0?suiteAccessTokenExpiresTimes.intValue():7000);
            redisUtils.set(RedisKeyConstant.WX_CP_TP_SUITE_ACCESS_TOKEN.concat(suiteId), suiteAccessTokenEntity,suiteAccessTokenExpiresTimes>0?suiteAccessTokenExpiresTimes.intValue():7000);
        }else{
            WxAccessToken suiteAccessTokenEntity = (WxAccessToken)suiteAccessTokenObj;
            if(StringUtils.isNotEmpty(suiteAccessTokenEntity.getAccessToken())) {
                configStorage.updateSuiteAccessToken(suiteAccessTokenEntity);
            }else{
                suiteAccessTokenEntity.setAccessToken(openAuthOfWxCpTp.getSuiteAccessToken());
                suiteAccessTokenEntity.setExpiresIn(suiteAccessTokenExpiresTimes>0?suiteAccessTokenExpiresTimes.intValue():7000);
                configStorage.updateSuiteAccessToken(suiteAccessTokenEntity);
                redisUtils.set(RedisKeyConstant.WX_CP_TP_SUITE_ACCESS_TOKEN.concat(suiteId), suiteAccessTokenEntity,suiteAccessTokenExpiresTimes>0?suiteAccessTokenExpiresTimes.intValue():7000);
            }
        }
        //update CorpAccessToken
        Long corpAccessTokenExpiresIn =  openAuthOfWxCpTp.getCorpAccessExpirein();
        Long corpAccessTokenExpiresTimes = corpAccessTokenExpiresIn!=null?(corpAccessTokenExpiresIn-currentSysteTime)/1000:7000;
        if(StringUtils.isNotEmpty(authCorpAppId)) {
            Object corpAccessTokenObj = redisUtils.get(RedisKeyConstant.WX_CP_TP_CORP_ACCESS.concat(suiteId).concat(":").concat(authCorpAppId));
            if (ObjectUtils.isEmpty(corpAccessTokenObj)) {
                configStorage.updateAccessToken(authCorpAppId, openAuthOfWxCpTp.getCorpAccessToken(), corpAccessTokenExpiresTimes>0?corpAccessTokenExpiresTimes.intValue():7000);
                WxAccessToken corpAccessTokenEntity = new WxAccessToken();
                corpAccessTokenEntity.setAccessToken(openAuthOfWxCpTp.getCorpAccessToken());
                corpAccessTokenEntity.setExpiresIn(corpAccessTokenExpiresTimes>0?corpAccessTokenExpiresTimes.intValue():7000);
                redisUtils.set(RedisKeyConstant.WX_CP_TP_CORP_ACCESS.concat(suiteId).concat(":").concat(authCorpAppId), corpAccessTokenEntity, corpAccessTokenExpiresTimes>0?corpAccessTokenExpiresTimes.intValue():7000);
            } else {
                WxAccessToken corpAccessTokenEntity = (WxAccessToken) corpAccessTokenObj;
                if (StringUtils.isNotEmpty(corpAccessTokenEntity.getAccessToken())) {
                    configStorage.updateSuiteAccessToken(corpAccessTokenEntity);
                } else {
                    corpAccessTokenEntity.setAccessToken(openAuthOfWxCpTp.getCorpAccessToken());
                    corpAccessTokenEntity.setExpiresIn(corpAccessTokenExpiresTimes>0?corpAccessTokenExpiresTimes.intValue():7000);
                    configStorage.updateAccessToken(authCorpAppId, openAuthOfWxCpTp.getCorpAccessToken(), corpAccessTokenExpiresTimes>0?corpAccessTokenExpiresTimes.intValue():7000);
                    redisUtils.set(RedisKeyConstant.WX_CP_TP_CORP_ACCESS.concat(suiteId).concat(":").concat(authCorpAppId), corpAccessTokenEntity, corpAccessTokenExpiresTimes>0?corpAccessTokenExpiresTimes.intValue():7000);
                }
            }
        }
        return configStorage;
    }

    private WxCpTpConfigStorage getWxCpDkRedissonConfigStorage(Long tenantId, WxCpTpService wxCpTpService, OpenConfigDTO openConfigDTO, OpenAuthDTO openAuthDTO ) {
        OpenConfigOfExtend openConfigOfExtend = openConfigDTO!=null?openConfigDTO.getOpenConfigOfExtend():null;
        OpenConfigOfWxCp openConfigOfWxCp = openConfigOfExtend != null ?openConfigOfExtend.getOpenConfigOfWxCp():null;
        OpenAuthOfExtend openAuthOfExtend = openAuthDTO.getOpenAuthOfExtend();
        if(openAuthOfExtend == null) throw new BusinessException("企业微信自建应用没有配置，请先配置!");
        OpenAuthOfWxCpDk  openAuthOfWxCpDk = openAuthOfExtend.getOpenAuthOfWxCpDk();
        String authCorpAppId = null;
        OpenAuthOfWxCpTpAuthCorpInfo authCorpInfo = openAuthOfWxCpDk.getAuthCorpInfo();
        if(authCorpInfo!=null) authCorpAppId = authCorpInfo.getCorpid();
        WxCpTpConfigStorage configStorage = wxCpTpService.getWxCpTpConfigStorage();
        Integer configType = openConfigDTO.getType();
        Integer configSubType = openConfigDTO.getSubType();
        JedisWxRedisOps  wxRedisOps = new JedisWxRedisOps(redisProperties.getJedisPool());
        String openConfigKey = "wx:cp:dk:t".concat(configType.toString()).concat(":s").concat(configSubType.toString());
        String suiteId = openConfigDTO.getComponentAppId();
        WxCpTpRedissonConfigImpl.WxCpTpRedissonConfigImplBuilder configStorageBuider = WxCpTpRedissonConfigImpl.builder().wxRedisOps(wxRedisOps);
        if(StringUtils.isNotEmpty(openConfigKey))configStorageBuider.keyPrefix(openConfigKey);
        if(StringUtils.isNotEmpty(openConfigDTO.getOpenAppId()))configStorageBuider.corpId(openConfigDTO.getOpenAppId());
        if(StringUtils.isNotEmpty(openConfigDTO.getOpenAppSecret()))configStorageBuider.corpSecret(openConfigDTO.getOpenAppSecret());
        if(StringUtils.isNotEmpty(openConfigDTO.getComponentAppId()))configStorageBuider.suiteId(suiteId);
        if(StringUtils.isNotEmpty(openConfigDTO.getComponentSecret()))configStorageBuider.suiteSecret(openConfigDTO.getComponentSecret());
        if(StringUtils.isNotEmpty(openConfigDTO.getComponentMsgToken()))configStorageBuider.token(openConfigDTO.getComponentMsgToken());
        if(StringUtils.isNotEmpty(openConfigDTO.getComponentMsgAesKey()))configStorageBuider.aesKey(openConfigDTO.getComponentMsgAesKey());
        if(StringUtils.isNotEmpty(openConfigDTO.getHttpProxyHost()))configStorageBuider.httpProxyHost(openConfigDTO.getHttpProxyHost());
        if(null!=openConfigDTO.getHttpProxyPort())configStorageBuider.httpProxyPort(openConfigDTO.getHttpProxyPort());
        if(StringUtils.isNotEmpty(openConfigDTO.getHttpProxyUsername()))configStorageBuider.httpProxyUsername(openConfigDTO.getHttpProxyUsername());
        if(StringUtils.isNotEmpty(openConfigDTO.getHttpProxyPassword()))configStorageBuider.httpProxyPassword(openConfigDTO.getHttpProxyPassword());
        if(openConfigOfWxCp!=null){
            OpenConfigOfWxCpProvider wxCpProvider = openConfigOfWxCp.getWxCpProvider();
            if(wxCpProvider!=null){
                String providerSecret = wxCpProvider.getProviderSecret();
                if(StringUtils.isNotEmpty(providerSecret))configStorageBuider.providerSecret(providerSecret);
            }
        }
        configStorage = configStorageBuider.build();
        Long currentSysteTime = System.currentTimeMillis();
        String suiteTicket = redisUtils.getString(RedisKeyConstant.WX_CP_DK_SUITE_TICKET.concat(suiteId));
        Object suiteAccessTokenObj = redisUtils.get(RedisKeyConstant.WX_CP_DK_SUITE_ACCESS_TOKEN.concat(suiteId));
        // ticket
        if(StringUtils.isEmpty(suiteTicket)){
            configStorage.updateSuiteTicket(openAuthOfWxCpDk.getSuiteTicket(), 1200);
            redisUtils.set(RedisKeyConstant.WX_CP_DK_SUITE_TICKET.concat(suiteId), openAuthOfWxCpDk.getSuiteTicket(),1000);
        }else{
            configStorage.updateSuiteTicket(suiteTicket, 1200);
        }
        //update suiteAccessToken
        Long suiteAccessTokenExpiresIn =  openAuthOfWxCpDk.getSuiteAccessExpirein();
        Long suiteAccessTokenExpiresTimes = suiteAccessTokenExpiresIn!=null?(suiteAccessTokenExpiresIn-currentSysteTime)/1000:7000;
        if(ObjectUtils.isEmpty(suiteAccessTokenObj)) {
            configStorage.updateSuiteAccessToken(openAuthOfWxCpDk.getSuiteAccessToken(), suiteAccessTokenExpiresTimes>0?suiteAccessTokenExpiresTimes.intValue():7000);
            WxAccessToken suiteAccessTokenEntity = new WxAccessToken();
            suiteAccessTokenEntity.setAccessToken(openAuthOfWxCpDk.getSuiteAccessToken());
            suiteAccessTokenEntity.setExpiresIn(suiteAccessTokenExpiresTimes>0?suiteAccessTokenExpiresTimes.intValue():7000);
            redisUtils.set(RedisKeyConstant.WX_CP_DK_SUITE_ACCESS_TOKEN.concat(suiteId), suiteAccessTokenEntity,suiteAccessTokenExpiresTimes>0?suiteAccessTokenExpiresTimes.intValue():7000);
        }else{
            WxAccessToken suiteAccessTokenEntity = (WxAccessToken)suiteAccessTokenObj;
            if(StringUtils.isNotEmpty(suiteAccessTokenEntity.getAccessToken())) {
                configStorage.updateSuiteAccessToken(suiteAccessTokenEntity);
            }else{
                suiteAccessTokenEntity.setAccessToken(openAuthOfWxCpDk.getSuiteAccessToken());
                suiteAccessTokenEntity.setExpiresIn(suiteAccessTokenExpiresTimes>0?suiteAccessTokenExpiresTimes.intValue():7000);
                configStorage.updateSuiteAccessToken(suiteAccessTokenEntity);
                redisUtils.set(RedisKeyConstant.WX_CP_DK_SUITE_ACCESS_TOKEN.concat(suiteId), suiteAccessTokenEntity,suiteAccessTokenExpiresTimes>0?suiteAccessTokenExpiresTimes.intValue():7000);
            }
        }
        //update ProviderAccessToken
        Object providerAccessTokenObj = redisUtils.get(RedisKeyConstant.WX_CP_DK_PROVIDER_ACCESS_TOKEN.concat(suiteId));
        Long providerAccessTokenExpiresIn =  openAuthOfWxCpDk.getProviderAccessExpirein();
        Long providerAccessTokenExpiresTimes = providerAccessTokenExpiresIn!=null?(providerAccessTokenExpiresIn-currentSysteTime)/1000:7000;
        if (ObjectUtils.isEmpty(providerAccessTokenObj)) {
            configStorage.updateProviderToken(openAuthOfWxCpDk.getProviderAccessToken(), providerAccessTokenExpiresTimes>0?providerAccessTokenExpiresTimes.intValue():7000);
            WxCpProviderToken providerAccessTokenEntity = new WxCpProviderToken();
            providerAccessTokenEntity.setProviderAccessToken(openAuthOfWxCpDk.getProviderAccessToken());
            providerAccessTokenEntity.setExpiresIn(providerAccessTokenExpiresTimes>0?providerAccessTokenExpiresTimes.intValue():7000);
            redisUtils.set(RedisKeyConstant.WX_CP_DK_PROVIDER_ACCESS_TOKEN.concat(suiteId), providerAccessTokenEntity, providerAccessTokenExpiresTimes>0?providerAccessTokenExpiresTimes.intValue():7000);
        } else {
            WxCpProviderToken providerAccessTokenEntity = (WxCpProviderToken) providerAccessTokenObj;
            if (StringUtils.isNotEmpty(providerAccessTokenEntity.getProviderAccessToken())) {
                configStorage.updateProviderToken(providerAccessTokenEntity.getProviderAccessToken(),providerAccessTokenExpiresTimes>0?providerAccessTokenExpiresTimes.intValue():7000);
            } else {
                providerAccessTokenEntity.setProviderAccessToken(openAuthOfWxCpDk.getProviderAccessToken());
                providerAccessTokenEntity.setExpiresIn(providerAccessTokenExpiresTimes>0?providerAccessTokenExpiresTimes.intValue():7000);
                configStorage.updateProviderToken(openAuthOfWxCpDk.getProviderAccessToken(), providerAccessTokenExpiresTimes>0?providerAccessTokenExpiresTimes.intValue():7000);
                redisUtils.set(RedisKeyConstant.WX_CP_DK_PROVIDER_ACCESS_TOKEN.concat(suiteId), providerAccessTokenEntity, providerAccessTokenExpiresTimes>0?providerAccessTokenExpiresTimes.intValue():7000);
            }
        }

        return configStorage;
    }

    private WxOpenServiceImpl getBean() {
        return SpringBeanUtil.getBean(this.getClass());
    }
}